package com.kgcx.common.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kgcx.common.listener.ApplicationStartUp;
import com.kgcx.common.utils.ApplicationUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class JsonConfig {
    /**
     * 告诉Jackson空对象不要抛异常
     * 设置日期格式
     *
     * @return
     */
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
                //.setDateFormat(new SimpleDateFormat(Cons.DATE_FORMAT_YYYYMMDDHHMMSSSSS))
                //告诉Jackson序列化时空对象不要抛异常
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
                //告诉Jackson反序列化时找不到对应属性不要抛异常
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @PostConstruct
    public void enableWriteDatesAsTimestamps() {
        /**
         * springBoot2.0.0Release版后，自动配置会默认把SerializationFeature.WRITE_DATES_AS_TIMESTAMPS(时间输出为非时间戳整型)设置为false
         * 且设置顺序为objectMapper初始化后，所以通过初始化objectMapper时指定为true也没用，会在后面被JacksonAutoConfiguration重新自动配置改为false
         * 只有在环境初始化完毕后再修改回来
         */
        ApplicationStartUp.addFunction(() -> ApplicationUtils.getBean(ObjectMapper.class).enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
    }

}
